<template>
  <div class="container">
    <headMenu />
    <a-card class="general-card" :title="'查询' + $t(menusName)">
      <!--  查询   -->
      <a-row>
        <a-col :flex="1">
          <a-form :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
            <a-row :gutter="18">
              <a-col :span="9">
                <a-form-item field="number" label="主键">
                  <a-input placeholder="主键" v-model="pageData.id" />
                </a-form-item>
              </a-col>
              <a-col :span="9">
                <a-form-item field="name" label="名称">
                  <a-input v-model="pageData.name" placeholder="名称" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>

        <a-col :flex="'86px'" style="text-align: right; position: relative; right: 200px">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button type="primary" @click="updateAndAdd(undefined)">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-button @click="subitmDeleteIds">
            <template #icon>
              <icon-delete />
            </template>
            批量删除
          </a-button>
        </a-col>
      </a-row>

      <!--  渲染数据  -->
      <a-spin :loading="loading" tip="This may take a while..." style="width: 100%">
        <a-table row-key="urId" :bordered="false" :data="data" @selection-change="selectionChange" :row-selection="{
            type: 'checkbox',
            showCheckedAll: true,
            checkStrictly: true,
          }">
          <template #columns>

            <a-table-column data-index="reId" title="主键">
            </a-table-column>
            <a-table-column data-index="reName" title="角色名">
            </a-table-column>


            <a-table-column title="修改">
              <template #cell="{ record }">
                <a-button @click="updateAndAdd(record.reId)" type="outline">编辑</a-button>
                <a-button style="left:10px;" @click="sq(record.reId)" type="outline">授权</a-button>
              </template>
            </a-table-column>

            <a-table-column title="删除">
              <template #cell="{ record }">
                <a-popconfirm @ok="submitDelete(record.reId)" content="Are you sure you want to delete?">
                  <a-button>
                    <template #icon>
                      <icon-delete />
                    </template>
                  </a-button>
                </a-popconfirm>
              </template>
            </a-table-column>
          </template>
        </a-table>

        <!--  分页  -->
        <a-pagination :total="pageData.totalCount" show-jumper show-page-size show-total show-current
          :current="pageData.page" :page-size="pageData.limit" :page-size-options="[10, 20, 50, 100]" @change="changePage"
          @page-size-change="limitChange" />
      </a-spin>
      <!--  编辑和添加的对话框
       -->
      <a-modal :visible="ediVisible" @ok="handleSubmit1" @cancel="handleCancel" :width="800">
        <template #title>{{ form.reId ? '编辑' : '添加' }}</template>
        <div>
          <a-form :model="form" :style="{ width: '100%' }">
            <a-form-item label="角色名" field="reName">
              <a-input v-model="form.reName" placeholder="角色名"></a-input>
            </a-form-item>
            <!-- <a-form-item label="授权识别" field="authority">
          <a-input v-model="form.authority" placeholder="授权识别"></a-input>   
              <a-cascader @change="changeAuthority" v-model="form.authority" :options="purview" label="授权识别"
                :default-value="['datunli']" :style="{ width: '400px' }" placeholder="Please select ..." multiple  
                />
            </a-form-item> -->
          </a-form>
        </div>
      </a-modal>

      <a-drawer :width="400" :visible="openQx" @ok="handleOk" @cancel="handleCancels" unmountOnClose>
        <template #title>
          权限控制
        </template>
        <!--              <a-input v-model="form.purview" placeholder="权限控制(增,删，修改)"></a-input>-->
        <!-- <a-cascader v-model="form.purview" @change="changePurview" :options="purviews" label="授权识别"
                :default-value="['datunli']" placeholder="Please select ..." multiple /> -->
        <a-tree :checkable="true" v-model:checked-keys="checkedKeys" @check="changeTreen" :data="purview" :fieldNames="{
            key: 'id',
            title: 'nickName',
            children: 'children',
            icon: 'customIcon'
          }" />
        <!-- <a-button type="dashed" @click="selectAllpurview(false)">重置</a-button>
              <a-button type="outline" @click="selectAllpurview(true)">全选</a-button> -->
      </a-drawer>
    </a-card>
  </div>
</template>

<script>
import role from '@/api/sys/role';
import api from '@/api/sys/role';
import headMenu from '@/components/headMenu/headMenu.vue';

export default {
  components: { headMenu },
  data() {
    return {
      openQx: false,
      purviews: [],
      purview: [],
      form: {},
      loading: true,
      deleteIds: [],
      ediVisible: false,
      menusName: this.$router.currentRoute.value.meta.locale,
      reId: "",
      pageData: {
        id: '',
        name: '',
        createTime: '',
        endTiem: '',
        status: '',
        page: '1',
        limit: 10,
        totalCount: 0,
        totalPage: 0,
      },
      checkedKeys: ['add,4'],
      checkStrictly: false,
      data: [],
      checkedNodes: [],
      selfAr: [],
    };
  },

  methods: {
    /**
     *   TOODO
     * @param { } e 
     * @param {*} data 
     */
    changeTreen(e, data) {
      // console.log(e);
      //console.log(" this.checkedKeys", this.checkedKeys);
      //   console.log(data.checkedNodes);
      this.checkedNodes = []
      /**
       
   @LiField(type = LiFieldType.INT, size = 200, comment = "角色id")
   private Integer reId;
   @LiField(type = LiFieldType.INT, size = 200, comment = "路由id")
   private Integer rtId;
   @LiField(type = LiFieldType.VARCHAR, size = 30, comment = "授权")
   private String raPermission;

       */
      data.checkedNodes.forEach(i => {
        if (i.code) {
          var arr = i.code.split(",")
          this.checkedNodes.push({
            reId: this.reId,
            rtId: arr[1],
            raPermission: arr[0]
          })
        }

      })
      // console.log(this.checkedNodes);
    },
    sq(id) {
      this.openQx = true
      this.reId = id;
      api.info(id).then((res) => {
        this.selfAr = res.data.data.list
        this.findAllRoles()
      });
    },
    handleCancels() {
      this.openQx = false
    },
    handleOk() {
      this.openQx = false

      role.updateBs(this.checkedNodes).then(res => {
        this.$message.success("修改成功！")
      })
    },
    /**
     * 全选 purview
     */
    selectAllpurview(flag) {
      if (!flag) {
        this.form.purview = []
      } else {
        this.form.purview = []
        this.purviews.forEach(element => {
          element.children.forEach(item => {
            this.form.purview.push(item.value)
          });
        });
      }
    },
    /**
     * 选择权限
     */
    changePurview(e) {
      this.form.purviewS = e
    },

    /**
     * 取消弹窗
     */
    handleCancel() {
      this.ediVisible = false;
      this.form = {}
    },

    /**
     * 提交判断是添加还是修改
     */
    handleSubmit() {
      this.form.purviewS = this.form.purview
      if (this.form.reId !== undefined) {
        this.updateSubmit();
      } else {
        this.addSumeit();
      }
    },

    /**
 * 提交判断是添加还是修改
 */
    handleSubmit1() {
      this.reoleUpdateSubmit();
    },

    /**
     * 查询全部角色
     */
    findAllRoles() {
      this.checkedKeys = []
      api.purview().then(res => {
        this.purview = res.data.data.data
        this.getpop(this.purview)
        //  console.log("purview", this.purview);

        //this.selfAr 需要把我们之前有的权限全部回显
        //{nickName: '添加', code: 'add,4'}
        this.selfAr.forEach(i => {
          this.checkedKeys.push(i.raPermission + "," + i.rtId)
        })

      })
    },
    getpop(data) {

      data.forEach(i => {
        if (i.children) {
          this.getpop(i.children)
        } else {
          i.children = [
            { nickName: "添加", code: "add," + i.id, id: "add," + i.id },
            { nickName: "修改", code: "update," + i.id, id: "update," + i.id },
            { nickName: "删除", code: "delete," + i.id, id: "delete," + i.id },
          ]
        }
        //   console.log(i);
      })
      // console.log(data);
    },

    /**
     * 提交修改
     */
    updateSubmit() {

      var arrs = ""
      var form = this.form
      var authority = this.form.authority
      for (var i = 0; i < authority.length; i++) {
        if (i == authority.length - 1) arrs += authority[i]
        else arrs += authority[i] + ","
      }
      api.updateAdd(form).then((res) => {
        if (res.data.code === 200) {
          //删除成功
          this.$notification.success('修改成功!');
          this.reset();
          this.form = {}
        } else {
          this.$notification.error('修改失败!');
        }
      });
    },



    /**
  * 提交修改
  */
    reoleUpdateSubmit() {
      api.saveOrUpdate(this.form).then((res) => {
        if (res.data.code === 200) {
          //删除成功
          this.$notification.success('提交成功!');
          this.reset();
          this.form = {}
        } else {
          this.$notification.error('提交失败!');
        }
      });
    },

    /**
     *  添加提交
     */
    addSumeit() {
      var arrs = ""
      var form = this.form
      if (this.form.authority) {
        var authority = this.form.authority
        for (var i = 0; i < authority.length; i++) {
          if (i == authority.length - 1) arrs += authority[i]
          else arrs += authority[i] + ","
        }
        form.authority = arrs
      }
      api.updateAdd(form).then((res) => {
        if (res.data.code === 200) {
          //添加成功
          this.$notification.success('添加成功!');
          this.reset();
          this.ediVisible = false;
          this.form = {}
        } else {
          this.$notification.error('添加失败!');
        }
      });
    },
    /**
     * 新添加的方法
     */
    addInfo() {
      this.ediVisible = true;
    },

    /**
     * 判断当前的修改还是添加
     */
    updateAndAdd(id) {
      if (id !== undefined) {
        this.updateInfo(id);
      } else {
        this.addInfo();
      }
    },

    /**
     * 修改前先查询id
     */
    updateInfo(Id) {
      this.reId = Id;
      this.loading = true;
      api.info(Id).then((res) => {
        this.form = res.data.data.role;
        // var roleAuthorizations = res.data.data.list
        // var arrs = []
        // if (roleAuthorizations && roleAuthorizations.length > 0) {
        //   roleAuthorizations.forEach(item => {
        //     arrs.push(item.rtId + "," + item.raPermission)
        //   })
        //   this.form.purview = arrs
        // }

        //  if (this.form.authority != "all") this.form.authority = this.form.authority.split(",")
        this.ediVisible = true;
        this.loading = false;
        //  this.findAllRoles()
      });
    },

    /**
     * 删除选中的方法
     */
    subitmDeleteIds() {
      api.delete(this.deleteIds).then((res) => {
        if (res.data.code === 200) {
          //删除成功
          this.$notification.success('删除成功!');
          this.reset();
        } else {
          this.$notification.error('删除失败!');
        }
      });
    },
    /**
     * 查询数据
     */
    search() {
      //获取当前的开始时间和结束时间
      if (this.pageData.createTime) {
        this.pageData.createTime = this.pageData.createdTime[0];
        this.pageData.endTiem = this.pageData.createdTime[1];
      }

      //发送请求
      this.getList();
    },
    /**
     *  刷新查询的数据
     */
    reset() {
      this.ediVisible = false
      this.pageData = {
        id: '',
        name: '',
        createTime: '',
        endTime: '',
        status: '',
        page: '1',
        limit: 10,
        totalCount: 0,
        totalPage: 0,
      };
      this.getList();
    },

    /**
     *  选中
     */
    selectionChange(data) {
      this.deleteIds = data;
    },
    /**
     *  选择页码
     */
    changePage(currPage) {
      this.pageData.page = currPage;
      this.getList();
    },
    //选择分页大小
    limitChange(limit) {
      this.pageData.limit = limit;
      this.getList();
    },

    /**
     *  获取当前数据
     */
    getList() {
      this.loading = true;
      api.list(this.pageData).then((res) => {
        const page = res.data.data.page;
        this.data = page.list;
        this.pageData.page =
          page.currPage >= page.totalPage ? page.totalPage : page.currPage;
        this.pageData.limit = page.limit;
        this.pageData.totalCount = page.totalCount;
        this.pageData.totalPage = page.totalPage;
        this.loading = false;
      });
    },
    /**
     *  删除账号
     */
    submitDelete(id) {
      let data = [];
      data.push(id);
      api.delete(data).then((res) => {
        if (res.data.code === 200) {
          //删除成功
          this.$notification.success('删除成功!');
          this.reset();
        } else {
          this.$notification.error('删除失败!');
        }
      });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
</style>
